home *** CD-ROM | disk | FTP | other *** search
/ Meeting Pearls 1 / Meeting Pearls Vol 1 (1994).iso / installed_progs / linux / tools / amiga / gzip-1.1.2.lha / gzip-1.1.2 / deflate.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-05-25  |  27.2 KB  |  731 lines

  1. /* deflate.c -- compress data using the deflation algorithm
  2.  * Copyright (C) 1992-1993 Jean-loup Gailly
  3.  * This is free software; you can redistribute it and/or modify it under the
  4.  * terms of the GNU General Public License, see the file COPYING.
  5.  */
  6.  
  7. /*
  8.  *  PURPOSE
  9.  *
  10.  *      Identify new text as repetitions of old text within a fixed-
  11.  *      length sliding window trailing behind the new text.
  12.  *
  13.  *  DISCUSSION
  14.  *
  15.  *      The "deflation" process depends on being able to identify portions
  16.  *      of the input text which are identical to earlier input (within a
  17.  *      sliding window trailing behind the input currently being processed).
  18.  *
  19.  *      The most straightforward technique turns out to be the fastest for
  20.  *      most input files: try all possible matches and select the longest.
  21.  *      The key feature of this algorithm is that insertions into the string
  22.  *      dictionary are very simple and thus fast, and deletions are avoided
  23.  *      completely. Insertions are performed at each input character, whereas
  24.  *      string matches are performed only when the previous match ends. So it
  25.  *      is preferable to spend more time in matches to allow very fast string
  26.  *      insertions and avoid deletions. The matching algorithm for small
  27.  *      strings is inspired from that of Rabin & Karp. A brute force approach
  28.  *      is used to find longer strings when a small match has been found.
  29.  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  30.  *      (by Leonid Broukhis).
  31.  *         A previous version of this file used a more sophisticated algorithm
  32.  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
  33.  *      time, but has a larger average cost, uses more memory and is patented.
  34.  *      However the F&G algorithm may be faster for some highly redundant
  35.  *      files if the parameter max_chain_length (described below) is too large.
  36.  *
  37.  *  ACKNOWLEDGEMENTS
  38.  *
  39.  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  40.  *      I found it in 'freeze' written by Leonid Broukhis.
  41.  *      Thanks to many info-zippers for bug reports and testing.
  42.  *
  43.  *  REFERENCES
  44.  *
  45.  *      APPNOTE.TXT documentation file in PKZIP 1.93a distribution.
  46.  *
  47.  *      A description of the Rabin and Karp algorithm is given in the book
  48.  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  49.  *
  50.  *      Fiala,E.R., and Greene,D.H.
  51.  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  52.  *
  53.  *  INTERFACE
  54.  *
  55.  *      void lm_init (int pack_level, ush *flags)
  56.  *          Initialize the "longest match" routines for a new file
  57.  *
  58.  *      ulg deflate (void)
  59.  *          Processes a new input file and return its compressed length. Sets
  60.  *          the compressed length, crc, deflate flags and internal file
  61.  *          attributes.
  62.  */
  63.  
  64. #include <stdio.h>
  65.  
  66. #include "tailor.h"
  67. #include "gzip.h"
  68. #include "lzw.h" /* just for consistency checking */
  69.  
  70. #ifndef lint
  71. static char rcsid[] = "$Id: deflate.c,v 0.13 1993/05/25 16:25:40 jloup Exp $";
  72. #endif
  73.  
  74. /* ===========================================================================
  75.  * Configuration parameters
  76.  */
  77.  
  78. /* Compile with MEDIUM_MEM to reduce the memory requirements or
  79.  * with SMALL_MEM to use as little memory as possible. Use BIG_MEM if the
  80.  * entire input file can be held in memory (not possible on 16 bit systems).
  81.  * Warning: defining these symbols affects HASH_BITS (see below) and thus
  82.  * affects the compression ratio. The compressed output
  83.  * is still correct, and might even be smaller in some cases.
  84.  */
  85.  
  86. #ifdef SMALL_MEM
  87. #   define HASH_BITS  13  /* Number of bits used to hash strings */
  88. #endif
  89. #ifdef MEDIUM_MEM
  90. #   define HASH_BITS  14
  91. #endif
  92. #ifndef HASH_BITS
  93. #   define HASH_BITS  15
  94.    /* For portability to 16 bit machines, do not use values above 15. */
  95. #endif
  96.  
  97. /* To save space (see unlzw.c), we overlay prev+head with tab_prefix and
  98.  * window with tab_suffix. Check that we can do this:
  99.  */
  100. #if WSIZE<<1 > 1<<BITS
  101.    error: cannot overlay window with tab_suffix and prev with tab_prefix0
  102. #endif
  103. #if HASH_BITS > BITS-1
  104.    error: cannot overlay head with tab_prefix1
  105. #endif
  106.  
  107. #define HASH_SIZE (unsigned)(1<<HASH_BITS)
  108. #define HASH_MASK (HASH_SIZE-1)
  109. #define WMASK     (WSIZE-1)
  110. /* HASH_SIZE and WSIZE must be powers of two */
  111.  
  112. #define NIL 0
  113. /* Tail of hash chains */
  114.  
  115. #define FAST 4
  116. #define SLOW 2
  117. /* speed options for the general purpose bit flag */
  118.  
  119. #ifndef TOO_FAR
  120. #  define TOO_FAR 4096
  121. #endif
  122. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  123.  
  124. /* ===========================================================================
  125.  * Local data used by the "longest match" routines.
  126.  */
  127.  
  128. typedef ush Pos;
  129. typedef unsigned IPos;
  130. /* A Pos is an index in the character window. We use short instead of int to
  131.  * save space in the various tables. IPos is used only for parameter passing.
  132.  */
  133.  
  134. /* DECLARE(uch, window, 2L*WSIZE); */
  135. /* Sliding window. Input bytes are read into the second half of the window,
  136.  * and move to the first half later to keep a dictionary of at least WSIZE
  137.  * bytes. With this organization, matches are limited to a distance of
  138.  * WSIZE-MAX_MATCH bytes, but this ensures that IO is always
  139.  * performed with a length multiple of the block size. Also, it limits
  140.  * the window size to 64K, which is quite useful on MSDOS.
  141.  * To do: limit the window size to WSIZE+BSZ if SMALL_MEM (the code would
  142.  * be less efficient).
  143.  */
  144.  
  145. /* DECLARE(Pos, prev, WSIZE); */
  146. /* Link to older string with same hash index. To limit the size of this
  147.  * array to 64K, this link is maintained only for the last 32K strings.
  148.  * An index in this array is thus a window index modulo 32K.
  149.  */
  150.  
  151. /* DECLARE(Pos, head, 1<<HASH_BITS); */
  152. /* Heads of the hash chains or NIL. */
  153.  
  154. ulg window_size = (ulg)2*WSIZE;
  155. /* window size, 2*WSIZE except for MMAP or BIG_MEM, where it is the
  156.  * input file length plus MIN_LOOKAHEAD.
  157.  */
  158.  
  159. long block_start;
  160. /* window position at the beginning of the current output block. Gets
  161.  * negative when the window is moved backwards.
  162.  */
  163.  
  164. local unsigned ins_h;  /* hash index of string to be inserted */
  165.  
  166. #define H_SHIFT  ((HASH_BITS+MIN_MATCH-1)/MIN_MATCH)
  167. /* Number of bits by which ins_h and del_h must be shifted at each
  168.  * input step. It must be such that after MIN_MATCH steps, the oldest
  169.  * byte no longer takes part in the hash key, that is:
  170.  *   H_SHIFT * MIN_MATCH >= HASH_BITS
  171.  */
  172.  
  173. unsigned int near prev_length;
  174. /* Length of the best match at previous step. Matches not greater than this
  175.  * are discarded. This is used in the lazy match evaluation.
  176.  */
  177.  
  178.       unsigned near strstart;      /* start of string to insert */
  179.       unsigned near match_start;   /* start of matching string */
  180. local int           eofile;        /* flag set at end of input file */
  181. local unsigned      lookahead;     /* number of valid bytes ahead in window */
  182.  
  183. unsigned near max_chain_length;
  184. /* To speed up deflation, hash chains are never searched beyond this length.
  185.  * A higher limit improves compression ratio but degrades the speed.
  186.  */
  187.  
  188. local unsigned int max_lazy_match;
  189. /* Attempt to find a better match only when the current match is strictly
  190.  * smaller than this value.
  191.  */
  192.  
  193. int near good_match;
  194. /* Use a faster search when the previous match is longer than this */
  195.  
  196.  
  197. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  198.  * the desired pack level (0..9). The values given below have been tuned to
  199.  * exclude worst case performance for pathological files. Better values may be
  200.  * found for specific files.
  201.  */
  202.  
  203. typedef struct config {
  204.    ush good_length; /* reduce lazy search above this match length */
  205.    ush max_lazy;    /* do not perform lazy search above this match length */
  206.    ush nice_length; /* quit search above this match length */
  207.    ush max_chain;
  208. } config;
  209.  
  210. #ifdef  FULL_SEARCH
  211. # define nice_match MAX_MATCH
  212. #else
  213.   int near nice_match; /* Stop searching when current match exceeds this */
  214. #endif
  215.  
  216. local config configuration_table[10] = {
  217. /*      good lazy nice chain */
  218. /* 0 */ {0,    0,  0,    0},  /* store only */
  219. /* 1 */ {4,    4, 16,   16},  /* maximum speed */
  220. /* 2 */ {6,    8, 16,   16},
  221. /* 3 */ {8,   16, 32,   32},
  222. /* 4 */ {8,   16, 64,   64},
  223. /* 5 */ {8,   16, 128, 128},
  224. /* 6 */ {8,   32, 128, 256},
  225. /* 7 */ {8,   64, 128, 512},
  226. /* 8 */ {32, 128, 258, 1024},
  227. /* 9 */ {32, 258, 258, 4096}}; /* maximum compression */
  228.  
  229. /* Note: the current code requires max_lazy >= MIN_MATCH and max_chain >= 4
  230.  * but these restrictions can easily be removed at a small cost.
  231.  */
  232.  
  233. #define EQUAL 0
  234. /* result of memcmp for equal strings */
  235.  
  236. /* ===========================================================================
  237.  *  Prototypes for local functions.
  238.  */
  239. local void fill_window   OF((void));
  240.       int  longest_match OF((IPos cur_match));
  241. #ifdef ASMV
  242.       void match_init OF((void)); /* asm code initialization */
  243. #endif
  244.  
  245. #ifdef DEBUG
  246. local  void check_match OF((IPos start, IPos match, int length));
  247. #endif
  248.  
  249. /* ===========================================================================
  250.  * Update a hash value with the given input byte
  251.  * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
  252.  *    input characters, so that a running hash key can be computed from the
  253.  *    previous key instead of complete recalculation each time.
  254.  */
  255. #define UPDATE_HASH(h,c) (h = (((h)<<H_SHIFT) ^ (c)) & HASH_MASK)
  256.  
  257. /* ===========================================================================
  258.  * Insert string s in the dictionary and set match_head to the previous head
  259.  * of the hash chain (the most recent string with same hash key). Return
  260.  * the previous length of the hash chain.
  261.  * IN  assertion: all calls to to INSERT_STRING are made with consecutive
  262.  *    input characters and the first MIN_MATCH bytes of s are valid
  263.  *    (except for the last MIN_MATCH-1 bytes of the input file).
  264.  */
  265. #define INSERT_STRING(s, match_head) \
  266.    (UPDATE_HASH(ins_h, window[(s) + MIN_MATCH-1]), \
  267.     prev[(s) & WMASK] = match_head = head[ins_h], \
  268.     head[ins_h] = (s))
  269.  
  270. /* ===========================================================================
  271.  * Initialize the "longest match" routines for a new file
  272.  */
  273. void lm_init (pack_level, flags)
  274.     int pack_level; /* 0: store, 1: best speed, 9: best compression */
  275.     ush *flags;     /* general purpose bit flag */
  276. {
  277.     register unsigned j;
  278.  
  279.     if (pack_level < 1 || pack_level > 9) error("bad pack level");
  280.  
  281.     /* Initialize the hash table. */
  282. #if defined(MAXSEG_64K) && HASH_BITS == 15
  283.     for (j = 0;  j < HASH_SIZE; j++) head[j] = NIL;
  284. #else
  285.     memzero((char*)head, HASH_SIZE*sizeof(*head));
  286. #endif
  287.     /* prev will be initialized on the fly */
  288.  
  289.     /* Set the default configuration parameters:
  290.      */
  291.     max_lazy_match   = configuration_table[pack_level].max_lazy;
  292.     good_match       = configuration_table[pack_level].good_length;
  293. #ifndef FULL_SEARCH
  294.     nice_match       = configuration_table[pack_level].nice_length;
  295. #endif
  296.     max_chain_length = configuration_table[pack_level].max_chain;
  297.     if (pack_level == 1) {
  298.        *flags |= FAST;
  299.     } else if (pack_level == 9) {
  300.        *flags |= SLOW;
  301.     }
  302.     /* ??? reduce max_chain_length for binary files */
  303.  
  304.     strstart = 0;
  305.     block_start = 0L;
  306. #ifdef ASMV
  307.     match_init(); /* initialize the asm code */
  308. #endif
  309.  
  310.     lookahead = read_buf((char*)window,
  311.              sizeof(int) <= 2 ? (unsigned)WSIZE : 2*WSIZE);
  312.  
  313.     if (lookahead == 0 || lookahead == (unsigned)EOF) {
  314.        eofile = 1, lookahead = 0;
  315.        return;
  316.     }
  317.     eofile = 0;
  318.     /* Make sure that we always have enough lookahead. This is important
  319.      * if input comes from a device such as a tty.
  320.      */
  321.     while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
  322.  
  323.     ins_h = 0;
  324.     for (j=0; j<MIN_MATCH-1; j++) UPDATE_HASH(ins_h, window[j]);
  325.     /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
  326.      * not important since only literal bytes will be emitted.
  327.      */
  328. }
  329.  
  330. /* ===========================================================================
  331.  * Set match_start to the longest match starting at the given string and
  332.  * return its length. Matches shorter or equal to prev_length are discarded,
  333.  * in which case the result is equal to prev_length and match_start is
  334.  * garbage.
  335.  * IN assertions: cur_match is the head of the hash chain for the current
  336.  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  337.  */
  338. #ifndef ASMV
  339. /* For MSDOS, OS/2 and 386 Unix, an optimized version is in match.asm or
  340.  * match.s. The code is functionally equivalent, so you can use the C version
  341.  * if desired.
  342.  */
  343. int longest_match(cur_match)
  344.     IPos cur_match;                             /* current match */
  345. {
  346.     unsigned chain_length = max_chain_length;   /* max hash chain length */
  347.     register uch *scan = window + strstart;     /* current string */
  348.     register uch *match;                        /* matched string */
  349.     register int len;                           /* length of current match */
  350.     int best_len = prev_length;                 /* best match length so far */
  351.     IPos limit = strstart > (IPos)MAX_DIST ? strstart - (IPos)MAX_DIST : NIL;
  352.     /* Stop when cur_match becomes <= limit. To simplify the code,
  353.      * we prevent matches with the string of window index 0.
  354.      */
  355.  
  356. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  357.  * It is easy to get rid of this optimization if necessary.
  358.  */
  359. #if HASH_BITS < 8 || MAX_MATCH != 258
  360.    error: Code too clever
  361. #endif
  362.  
  363. #ifdef UNALIGNED_OK
  364.     /* Compare two bytes at a time. Note: this is not always beneficial.
  365.      * Try with and without -DUNALIGNED_OK to check.
  366.      */
  367.     register uch *strend = window + strstart + MAX_MATCH - 1;
  368.     register ush scan_start = *(ush*)scan;
  369.     register ush scan_end   = *(ush*)(scan+best_len-1);
  370. #else
  371.     register uch *strend = window + strstart + MAX_MATCH;
  372.     register uch scan_end1  = scan[best_len-1];
  373.     register uch scan_end   = scan[best_len];
  374. #endif
  375.  
  376.     /* Do not waste too much time if we already have a good match: */
  377.     if (prev_length >= good_match) {
  378.         chain_length >>= 2;
  379.     }
  380.     Assert(strstart <= window_size-MIN_LOOKAHEAD, "insufficient lookahead");
  381.  
  382.     do {
  383.         Assert(cur_match < strstart, "no future");
  384.         match = window + cur_match;
  385.  
  386.         /* Skip to next match if the match length cannot increase
  387.          * or if the match length is less than 2:
  388.          */
  389. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  390.         /* This code assumes sizeof(unsigned short) == 2. Do not use
  391.          * UNALIGNED_OK if your compiler uses a different size.
  392.          */
  393.         if (*(ush*)(match+best_len-1) != scan_end ||
  394.             *(ush*)match != scan_start) continue;
  395.  
  396.         /* It is not necessary to compare scan[2] and match[2] since they are
  397.          * always equal when the other bytes match, given that the hash keys
  398.          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  399.          * strstart+3, +5, ... up to strstart+257. We check for insufficient
  400.          * lookahead only every 4th comparison; the 128th check will be made
  401.          * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  402.          * necessary to put more guard bytes at the end of the window, or
  403.          * to check more often for insufficient lookahead.
  404.          */
  405.         scan++, match++;
  406.         do {
  407.         } while (*(ush*)(scan+=2) == *(ush*)(match+=2) &&
  408.                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
  409.                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
  410.                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
  411.                  scan < strend);
  412.         /* The funny "do {}" generates better code on most compilers */
  413.  
  414.         /* Here, scan <= window+strstart+257 */
  415.         Assert(scan <= window+(unsigned)(window_size-1), "wild scan");
  416.         if (*scan == *match) scan++;
  417.  
  418.         len = (MAX_MATCH - 1) - (int)(strend-scan);
  419.         scan = strend - (MAX_MATCH-1);
  420.  
  421. #else /* UNALIGNED_OK */
  422.  
  423.         if (match[best_len]   != scan_end  ||
  424.             match[best_len-1] != scan_end1 ||
  425.             *match            != *scan     ||
  426.             *++match          != scan[1])      continue;
  427.  
  428.         /* The check at best_len-1 can be removed because it will be made
  429.          * again later. (This heuristic is not always a win.)
  430.          * It is not necessary to compare scan[2] and match[2] since they
  431.          * are always equal when the other bytes match, given that
  432.          * the hash keys are equal and that HASH_BITS >= 8.
  433.          */
  434.         scan += 2, match++;
  435.  
  436.         /* We check for insufficient lookahead only every 8th comparison;
  437.          * the 256th check will be made at strstart+258.
  438.          */
  439.         do {
  440.         } while (*++scan == *++match && *++scan == *++match &&
  441.                  *++scan == *++match && *++scan == *++match &&
  442.                  *++scan == *++match && *++scan == *++match &&
  443.                  *++scan == *++match && *++scan == *++match &&
  444.                  scan < strend);
  445.  
  446.         len = MAX_MATCH - (int)(strend - scan);
  447.         scan = strend - MAX_MATCH;
  448.  
  449. #endif /* UNALIGNED_OK */
  450.  
  451.         if (len > best_len) {
  452.             match_start = cur_match;
  453.             best_len = len;
  454.             if (len >= nice_match) break;
  455. #ifdef UNALIGNED_OK
  456.             scan_end = *(ush*)(scan+best_len-1);
  457. #else
  458.             scan_end1  = scan[best_len-1];
  459.             scan_end   = scan[best_len];
  460. #endif
  461.         }
  462.     } while ((cur_match = prev[cur_match & WMASK]) > limit
  463.          && --chain_length != 0);
  464.  
  465.     return best_len;
  466. }
  467. #endif /* ASMV */
  468.  
  469. #ifdef DEBUG
  470. /* ===========================================================================
  471.  * Check that the match at match_start is indeed a match.
  472.  */
  473. local void check_match(start, match, length)
  474.     IPos start, match;
  475.     int length;
  476. {
  477.     /* check that the match is indeed a match */
  478.     if (memcmp((char*)window + match,
  479.                 (char*)window + start, length) != EQUAL) {
  480.         fprintf(stderr,
  481.             " start %d, match %d, length %d\n",
  482.             start, match, length);
  483.         error("invalid match");
  484.     }
  485.     if (verbose > 1) {
  486.         fprintf(stderr,"\\[%d,%d]", start-match, length);
  487.         do { putc(window[start++], stderr); } while (--length != 0);
  488.     }
  489. }
  490. #else
  491. #  define check_match(start, match, length)
  492. #endif
  493.  
  494. /* ===========================================================================
  495.  * Fill the window when the lookahead becomes insufficient.
  496.  * Updates strstart and lookahead, and sets eofile if end of input file.
  497.  * IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
  498.  * OUT assertions: at least one byte has been read, or eofile is set;
  499.  *    file reads are performed for at least two bytes (required for the
  500.  *    translate_eol option).
  501.  */
  502. local void fill_window()
  503. {
  504.     register unsigned n, m;
  505.     unsigned more = (unsigned)(window_size - (ulg)lookahead - (ulg)strstart);
  506.     /* Amount of free space at the end of the window. */
  507.  
  508.     /* If the window is almost full and there is insufficient lookahead,
  509.      * move the upper half to the lower one to make room in the upper half.
  510.      */
  511.     if (more == (unsigned)EOF) {
  512.         /* Very unlikely, but possible on 16 bit machine if strstart == 0
  513.          * and lookahead == 1 (input done one byte at time)
  514.          */
  515.         more--;
  516.     } else if (strstart >= WSIZE+MAX_DIST) {
  517.         /* By the IN assertion, the window is not empty so we can't confuse
  518.          * more == 0 with more == 64K on a 16 bit machine.
  519.          */
  520.         Assert(window_size == (ulg)2*WSIZE, "no sliding with BIG_MEM");
  521.  
  522.         memcpy((char*)window, (char*)window+WSIZE, (unsigned)WSIZE);
  523.         match_start -= WSIZE;
  524.         strstart    -= WSIZE; /* we now have strstart >= MAX_DIST: */
  525.  
  526.         block_start -= (long) WSIZE;
  527.  
  528.         for (n = 0; n < HASH_SIZE; n++) {
  529.             m = head[n];
  530.             head[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL);
  531.         }
  532.         for (n = 0; n < WSIZE; n++) {
  533.             m = prev[n];
  534.             prev[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL);
  535.             /* If n is not on any hash chain, prev[n] is garbage but
  536.              * its value will never be used.
  537.              */
  538.         }
  539.         more += WSIZE;
  540.     }
  541.     /* At this point, more >= 2 */
  542.     if (!eofile) {
  543.         n = read_buf((char*)window+strstart+lookahead, more);
  544.         if (n == 0 || n == (unsigned)EOF) {
  545.             eofile = 1;
  546.         } else {
  547.             lookahead += n;
  548.         }
  549.     }
  550. }
  551.  
  552. /* ===========================================================================
  553.  * Flush the current block, with given end-of-file flag.
  554.  * IN assertion: strstart is set to the end of the current match.
  555.  */
  556. #define FLUSH_BLOCK(eof) \
  557.    flush_block(block_start >= 0L ? (char*)&window[(unsigned)block_start] : \
  558.                 (char*)NULL, (long)strstart - block_start, (eof))
  559.  
  560. /* ===========================================================================
  561.  * Processes a new input file and return its compressed length.
  562.  */
  563. #ifdef NO_LAZY
  564. ulg deflate()
  565. {
  566.     IPos hash_head; /* head of the hash chain */
  567.     int flush;      /* set if current block must be flushed */
  568.     unsigned match_length = 0;  /* length of best match */
  569.  
  570.     prev_length = MIN_MATCH-1;
  571.     while (lookahead != 0) {
  572.         /* Insert the string window[strstart .. strstart+2] in the
  573.          * dictionary, and set hash_head to the head of the hash chain:
  574.          */
  575.         INSERT_STRING(strstart, hash_head);
  576.  
  577.         /* Find the longest match, discarding those <= prev_length.
  578.          * At this point we have always match_length < MIN_MATCH
  579.          */
  580.         if (hash_head != NIL && strstart - hash_head <= MAX_DIST) {
  581.             /* To simplify the code, we prevent matches with the string
  582.              * of window index 0 (in particular we have to avoid a match
  583.              * of the string with itself at the start of the input file).
  584.              */
  585.             match_length = longest_match (hash_head);
  586.             /* longest_match() sets match_start */
  587.             if (match_length > lookahead) match_length = lookahead;
  588.         }
  589.         if (match_length >= MIN_MATCH) {
  590.             check_match(strstart, match_start, match_length);
  591.  
  592.             flush = ct_tally(strstart-match_start, match_length - MIN_MATCH);
  593.  
  594.             lookahead -= match_length;
  595.             match_length--; /* string at strstart already in hash table */
  596.             do {
  597.                 strstart++;
  598.                 INSERT_STRING(strstart, hash_head);
  599.                 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  600.                  * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
  601.                  * these bytes are garbage, but it does not matter since the
  602.                  * next lookahead bytes will always be emitted as literals.
  603.                  */
  604.             } while (--match_length != 0);
  605.         } else {
  606.             /* No match, output a literal byte */
  607.             flush = ct_tally (0, window[strstart]);
  608.             lookahead--;
  609.         }
  610.         strstart++; 
  611.         if (flush) FLUSH_BLOCK(0), block_start = strstart;
  612.  
  613.         /* Make sure that we always have enough lookahead, except
  614.          * at the end of the input file. We need MAX_MATCH bytes
  615.          * for the next match, plus MIN_MATCH bytes to insert the
  616.          * string following the next match.
  617.          */
  618.         while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
  619.  
  620.     }
  621.     return FLUSH_BLOCK(1); /* eof */
  622. }
  623. #else /* LAZY */
  624. /* ===========================================================================
  625.  * Same as above, but achieves better compression. We use a lazy
  626.  * evaluation for matches: a match is finally adopted only if there is
  627.  * no better match at the next window position.
  628.  */
  629. ulg deflate()
  630. {
  631.     IPos hash_head;          /* head of hash chain */
  632.     IPos prev_match;         /* previous match */
  633.     int flush;               /* set if current block must be flushed */
  634.     int match_available = 0; /* set if previous match exists */
  635.     register unsigned match_length = MIN_MATCH-1; /* length of best match */
  636. #ifdef DEBUG
  637.     extern long isize;        /* byte length of input file, for debug only */
  638. #endif
  639.  
  640.     /* Process the input block. */
  641.     while (lookahead != 0) {
  642.         /* Insert the string window[strstart .. strstart+2] in the
  643.          * dictionary, and set hash_head to the head of the hash chain:
  644.          */
  645.         INSERT_STRING(strstart, hash_head);
  646.  
  647.         /* Find the longest match, discarding those <= prev_length.
  648.          */
  649.         prev_length = match_length, prev_match = match_start;
  650.         match_length = MIN_MATCH-1;
  651.  
  652.         if (hash_head != NIL && prev_length < max_lazy_match &&
  653.             strstart - hash_head <= MAX_DIST) {
  654.             /* To simplify the code, we prevent matches with the string
  655.              * of window index 0 (in particular we have to avoid a match
  656.              * of the string with itself at the start of the input file).
  657.              */
  658.             match_length = longest_match (hash_head);
  659.             /* longest_match() sets match_start */
  660.             if (match_length > lookahead) match_length = lookahead;
  661.  
  662.             /* Ignore a length 3 match if it is too distant: */
  663.             if (match_length == MIN_MATCH && strstart-match_start > TOO_FAR){
  664.                 /* If prev_match is also MIN_MATCH, match_start is garbage
  665.                  * but we will ignore the current match anyway.
  666.                  */
  667.                 match_length--;
  668.             }
  669.         }
  670.         /* If there was a match at the previous step and the current
  671.          * match is not better, output the previous match:
  672.          */
  673.         if (prev_length >= MIN_MATCH && match_length <= prev_length) {
  674.  
  675.             check_match(strstart-1, prev_match, prev_length);
  676.  
  677.             flush = ct_tally(strstart-1-prev_match, prev_length - MIN_MATCH);
  678.  
  679.             /* Insert in hash table all strings up to the end of the match.
  680.              * strstart-1 and strstart are already inserted.
  681.              */
  682.             lookahead -= prev_length-1;
  683.             prev_length -= 2;
  684.             do {
  685.                 strstart++;
  686.                 INSERT_STRING(strstart, hash_head);
  687.                 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  688.                  * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
  689.                  * these bytes are garbage, but it does not matter since the
  690.                  * next lookahead bytes will always be emitted as literals.
  691.                  */
  692.             } while (--prev_length != 0);
  693.             match_available = 0;
  694.             match_length = MIN_MATCH-1;
  695.             strstart++;
  696.             if (flush) FLUSH_BLOCK(0), block_start = strstart;
  697.  
  698.         } else if (match_available) {
  699.             /* If there was no match at the previous position, output a
  700.              * single literal. If there was a match but the current match
  701.              * is longer, truncate the previous match to a single literal.
  702.              */
  703.             Tracevv((stderr,"%c",window[strstart-1]));
  704.             if (ct_tally (0, window[strstart-1])) {
  705.                 FLUSH_BLOCK(0), block_start = strstart;
  706.             }
  707.             strstart++;
  708.             lookahead--;
  709.         } else {
  710.             /* There is no previous match to compare with, wait for
  711.              * the next step to decide.
  712.              */
  713.             match_available = 1;
  714.             strstart++;
  715.             lookahead--;
  716.         }
  717.         Assert (strstart <= isize && lookahead <= isize, "a bit too far");
  718.  
  719.         /* Make sure that we always have enough lookahead, except
  720.          * at the end of the input file. We need MAX_MATCH bytes
  721.          * for the next match, plus MIN_MATCH bytes to insert the
  722.          * string following the next match.
  723.          */
  724.         while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
  725.     }
  726.     if (match_available) ct_tally (0, window[strstart-1]);
  727.  
  728.     return FLUSH_BLOCK(1); /* eof */
  729. }
  730. #endif /* LAZY */
  731.